<script lang="ts" setup>
import {ref, reactive, onMounted} from 'vue'
import {useAppointmentOrder} from "@/stores/AppointmentOrder"
import type {FormInstance} from 'element-plus'
import axios from 'axios'
import {ElMessage} from 'element-plus'

const appointmentOrder = useAppointmentOrder()
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  model: '',
  province: '',
  plateLetter: '',
  plateNumber: '',
  serviceItem: '',
  date1: '',
  date2: '',
  position: '',
  desc: '',
})

// 配置数据
const letters = ref(Array.from({length: 26}, (_, i) => String.fromCharCode(65 + i)))
const provinces = ref([
  '京', '沪', '津', '渝', '冀', '晋', '辽', '吉', '黑', '苏',
  '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤', '琼',
  '川', '贵', '云', '陕', '甘', '青', '台', '蒙', '桂', '宁',
  '新', '藏', '港', '澳'
])

// 服务项相关
interface ServiceItem {
  id: number
  serviceName: string
}

const serviceList = ref<ServiceItem[]>([])
const fetchServices = async () => {
  try {
    const response = await axios.get('/api/service/list')
    if (response.data.code === 200) {
      serviceList.value = response.data.data
    }
  } catch (error) {
    console.error('API调用失败:', error)
  }
}

// 时间处理逻辑
const disabledDate = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date < today
}

const disabledTime = (date: Date | null) => {
  if (!date) return {hours: () => [], minutes: () => []}

  const now = new Date()
  const isToday = date.toDateString() === now.toDateString()

  if (!isToday) return {hours: () => [], minutes: () => []}

  return {
    hours: () => {
      // 禁用当前小时之前的所有小时
      const disabledHours = []
      for (let i = 0; i < now.getHours(); i++) {
        disabledHours.push(i)
      }
      return disabledHours
    },
    minutes: (selectedHour: number) => {
      // 在当前小时时，禁用当前分钟之前的所有分钟
      if (selectedHour === now.getHours()) {
        const disabledMinutes = []
        for (let i = 0; i < now.getMinutes(); i++) {
          disabledMinutes.push(i)
        }
        return disabledMinutes
      }
      return []
    }
  }
}
const handlePlateInput = (e: Event) => {
  const target = e.target as HTMLInputElement
  form.plateNumber = target.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase()
}

// 验证规则
const rules = reactive({
  model: [{required: true, message: '请输入车型', trigger: 'blur'}],
  province: [{required: true, message: '请选择省份', trigger: 'change'}],
  plateLetter: [{required: true, message: '请选择字母', trigger: 'change'}],
  plateNumber: [{required: true, message: '请输入车牌号码', trigger: 'blur'}],
  serviceItem: [{required: true, message: '请选择服务项目', trigger: 'change'}],
  date1: [{required: true, message: '请选择预约日期', trigger: 'change'}],
  date2: [{required: true, message: '请选择预约时间', trigger: 'change'}],
  position: [{required: true, message: '请选择服务技师', trigger: 'change'}],
  desc: [{required: true, message: '请输入故障描述', trigger: 'blur'}]
})

// 表单操作
const handleClose = () => {
  appointmentOrder.appointBoxState = false
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
  Object.assign(form, {
    model: '',
    province: '',
    plateLetter: '',
    plateNumber: '',
    serviceItem: '',
    date1: '',
    date2: '',
    position: '',
    desc: '',
  })
}

const submit = async () => {
  try {
    // 前端验证
    await formRef.value?.validate()

    // 手动空值检查
    if (!Object.values(form).every(v =>
        Array.isArray(v) ? v.length > 0 : v !== '' && v !== null && v !== undefined
    )) {
      throw new Error('存在未通过验证的隐藏字段')
    }

    // 时间处理
    const appointmentDate = new Date(form.date1)
    const timeDate = new Date(form.date2)
    appointmentDate.setHours(timeDate.getHours(), timeDate.getMinutes())
    const appointmentTime = appointmentDate.toISOString().replace(/\.\d+Z$/, '')
    const now = new Date()
    if (appointmentDate < now) {
      throw new Error('预约时间不能早于当前时间')
    }
    // 提交数据
    const response = await axios.post('/api/appointment/create', {
      model: form.model,
      licensePlate: `${form.province}${form.plateLetter}${form.plateNumber}`,
      serviceName: form.serviceItem,
      appointmentTime,
      serviceTechnician: form.position,
      problemDescription: form.desc
    }, {
      validateStatus: (status) => status === 200 || status === 422
    })

    // 处理响应
    if (response.status === 422) {
      const errors = response.data.errors.map(e => e.msg).join(', ')
      throw new Error(`服务器验证失败: ${errors}`)
    }

    ElMessage.success('预约提交成功')
    resetForm()
    appointmentOrder.appointBoxState = false
  } catch (error: any) {
    const msg = error.response?.data?.message || error.message
    ElMessage.error(msg || '预约提交失败,检查表单数据是否完整')
  }
}

onMounted(() => {
  fetchServices()
})
</script>

<template>
  <el-dialog
      v-model="appointmentOrder.appointBoxState"
      title="预约订单"
      width="700"
      :before-close="handleClose"
  >
    <template #default>
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="auto"
          hide-required-asterisk
          style="max-width: 600px"
      >
        <el-form-item label="车型" prop="model">
          <el-input v-model="form.model"/>
        </el-form-item>

        <el-form-item label="车牌号" required>
          <el-row :gutter="8">
            <el-col :span="4">
              <el-form-item prop="province">
                <el-select v-model="form.province" placeholder="省份" filterable>
                  <el-option
                      v-for="item in provinces"
                      :key="item"
                      :label="item"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="plateLetter">
                <el-select v-model="form.plateLetter" placeholder="字母" filterable>
                  <el-option
                      v-for="item in letters"
                      :key="item"
                      :label="item"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item prop="plateNumber">
                <el-input
                    v-model="form.plateNumber"
                    placeholder="请输入车牌号码"
                    maxlength="6"
                    @input="handlePlateInput"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="服务项" prop="serviceItem">
          <el-select v-model="form.serviceItem" placeholder="选择服务项">
            <el-option
                v-for="item in serviceList"
                :key="item.id"
                :label="item.serviceName"
                :value="item.serviceName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预约时间" prop="date1">
          <el-row :gutter="12">
            <el-col :span="12">
              <el-date-picker
                  v-model="form.date1"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  :disabled-date="disabledDate"
              />
            </el-col>
            <el-col :span="12">
              <el-time-picker
                  v-model="form.date2"
                  format="HH:mm"
                  placeholder="选择时间"
                  style="width: 100%"
                  :disabled="!form.date1"
                  :disabled-time="disabledTime(new Date(form.date1))"
              />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="服务技师" prop="position">
          <el-radio-group v-model="form.position">
            <el-radio value="0">初级技师</el-radio>
            <el-radio value="1">中级技师</el-radio>
            <el-radio value="2">高级技师</el-radio>
            <el-radio value="3">专家</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="故障描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" :rows="4"/>
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">清空表单</el-button>
        <el-button type="primary" @click="submit">提交订单</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-form {
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
</style>